<template>
	<view class="container">
		<!-- 基础参数配置 -->
		<view class="config-section">
			<view class="section-title">基础参数</view>
			<view class="form-item">
				<text class="form-label">应用ID(agentid)</text>
				<picker class="picker" @change="onAgentIdChange" :value="agentIdIndex" :range="agentIdOptions"
					:range-key="'name'">
					<view class="picker-view">
						{{ agentIdOptions[agentIdIndex].name }}
					</view>
				</picker>
			</view>
			<view class="form-item userid-list-container">
			        <text class="form-label">用户ID列表(userid_list)</text>
			        <view class="section-desc">支持添加多个用户ID，用于指定目标用户范围</view>
			        
			        <!-- 用户ID输入项列表 -->
			        <view class="userid-items">
			          <view class="userid-item" v-for="(userId, index) in submitData.userid_list" :key="index">
			            <input 
			              class="form-input userid-input" 
			              placeholder="请输入用户ID" 
			              v-model="submitData.userid_list[index]"
			              required
			            />
			            <button 
			              class="remove-btn userid-remove-btn" 
			              @click="removeUserId(index)"
			            >
						<i class="fa fa-trash-o"></i>
			              <text class="iconfont icon-times"></text>
			            </button>
			          </view>
			        </view>
			        
			        <!-- 新增用户ID按钮 -->
			        <button class="add-btn userid-add-btn" @click="addUserId">
			          <text class="iconfont icon-plus mr-1"></text> 添加用户ID
			        </button>
			      </view>
		</view>

		<!-- 展示类型选择 -->
		<view class="config-section">
			<view class="section-title">展示类型</view>
			<picker class="picker" @change="onDisplayTypeChange" :value="displayTypeIndex" :range="displayTypes">
				<view class="picker-view">
					{{ displayTypes[displayTypeIndex] }}
				</view>
			</picker>
		</view>

		<!-- 图片型配置 (type=image) -->
		<view class="config-section" v-if="submitData.type === 'image'">
			<view class="section-title">图片型配置</view>

			<view class="form-item">
				<text class="form-label">图片URL(url)</text>
				<input class="form-input" placeholder="请输入图片URL" v-model="submitData.image.url" required />
			</view>

			<view class="form-item">
				<text class="form-label">跳转链接(jump_url)</text>
				<input class="form-input" placeholder="请输入跳转链接" v-model="submitData.image.jump_url" required />
			</view>
		</view>

		<!-- 列表型配置 (type=list) -->
		<view class="config-section" v-if="submitData.type === 'list'">
			<view class="section-title">列表型配置</view>

			<view class="section-desc">每项包含标题、跳转链接（最多3项）</view>

			<view class="list-items">
				<view class="list-item" v-for="(item, index) in submitData.list.items" :key="index">
					<view class="item-header">
						<text>列表项 {{ index + 1 }}</text>
						<button class="remove-btn" @click="removeListItem(index)"
							v-if="submitData.list.items.length > 1">
							<i class="fa fa-trash-o"></i>
						</button>
					</view>

					<view class="form-item">
						<text class="form-label">标题(title)</text>
						<input class="form-input" placeholder="请输入列表项标题" v-model="submitData.list.items[index].title"
							required />
					</view>

					<view class="form-item">
						<text class="form-label">跳转链接(jump_url)</text>
						<input class="form-input" placeholder="请输入跳转链接" v-model="submitData.list.items[index].jump_url"
							required />
					</view>
				</view>
			</view>

			<button class="add-btn" @click="addListItem" v-if="submitData.list.items.length < 3">
				<i class="fa fa-plus-circle"></i> 添加列表项
			</button>
			<view class="limit-tip" v-else>
				列表项最多支持3个，无法继续添加
			</view>
		</view>

		<!-- 关键数据型配置 (type=keydata) -->
		<view class="config-section" v-if="submitData.type === 'keydata'">
			<view class="section-title">关键数据型配置</view>

			<view class="section-desc">每项包含键、数据值、跳转链接（最多4项）</view>

			<view class="list-items">
				<view class="data-item" v-for="(item, index) in submitData.keydata.items" :key="index">
					<view class="item-header">
						<text>数据项 {{ index + 1 }}</text>
						<button class="remove-btn" @click="removeDataItem(index)"
							v-if="submitData.keydata.items.length > 1">
							<i class="fa fa-trash-o"></i>
						</button>
					</view>

					<view class="form-item">
						<text class="form-label">键(key)</text>
						<input class="form-input" placeholder="请输入键名，如：待审批"
							v-model="submitData.keydata.items[index].key" required />
					</view>

					<view class="form-item">
						<text class="form-label">数据值(data)</text>
						<input class="form-input" placeholder="请输入数据值" v-model="submitData.keydata.items[index].data"
							required />
					</view>

					<view class="form-item">
						<text class="form-label">跳转链接(jump_url)</text>
						<input class="form-input" placeholder="请输入跳转链接"
							v-model="submitData.keydata.items[index].jump_url" required />
					</view>

					<view class="form-item">
						<text class="form-label">跳转小程序(pagepath)</text>
						<input class="form-input" placeholder="请输入跳转链接"
							v-model="submitData.keydata.items[index].pagepath" required />
					</view>
				</view>
			</view>

			<button class="add-btn" @click="addDataItem" v-if="submitData.keydata.items.length < 4">
				<i class="fa fa-plus-circle"></i> 添加数据项
			</button>
			<view class="limit-tip" v-else>
				数据项最多支持4个，无法继续添加
			</view>
		</view>

		<!-- WebView型配置 (type=webview) -->
		<view class="config-section" v-if="submitData.type === 'webview'">
			<view class="section-title">WebView型配置</view>

			<view class="form-item">
				<text class="form-label">页面标题(title)</text>
				<input class="form-input" placeholder="请输入页面标题" v-model="submitData.webview.title" required />
			</view>

			<view class="form-item">
				<text class="form-label">网页URL(url)</text>
				<input class="form-input" placeholder="请输入网页URL" v-model="submitData.webview.url" required />
			</view>

			<view class="form-item">
				<text class="form-label">跳转链接(jump_url)</text>
				<input class="form-input" placeholder="请输入跳转链接" v-model="submitData.webview.jump_url" required />
			</view>
		</view>

		<!-- 提交按钮 -->
		<button class="submit-btn" @click="submitConfig">
			<i class="fa fa-check-circle"></i> 提交配置
		</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 提交的数据结构，完全匹配要求的JSON格式
				submitData: {
					agentid: '1000157', // 应用ID默认值
					secret: '', // 应用密钥
					userid_list: [''], // 新增：用户ID列表，默认初始化1个空项
					type: "image", // 默认类型
					image: {
						url: "",
						jump_url: ""
					},
					list: {
						items: []
					},
					keydata: {
						items: []
					},
					webview: {
						title: "",
						url: "",
						jump_url: ""
					}
				},

				// 应用ID选择器配置
				agentIdOptions: [{
						name: '客流数据',
						value: '1000157'
					},
					{
						name: '集团公告',
						value: '1000158'
					},
					{
						name: '荣耀表彰',
						value: '1000161'
					}
				],
				agentIdIndex: 0,

				// 展示类型选项
				displayTypes: ['image(图片型)', 'list(列表型)', 'keydata(关键数据型)', 'webview(网页型)'],
				displayTypeIndex: 0
			};
		},
		onLoad() {
			// 初始化默认类型的数据结构
			this.initDefaultTypeData();
			this.fetchDefaultData(1000157);
		},
		methods: {
			fetchDefaultData(id) {
				// 调用接口（这里使用示例URL，实际替换为你的接口地址）
				uni.request({
					url: 'http://ziyan.xshhotels.cn:8981/api/NetUpdate/GetDetail?Id=' + id, // 替换为实际接口URL
					method: 'GET',
					success: (res) => {
						if (res.data && res.data.code === 0) {
							try {
								// 解析msg字段（因为数据嵌套在msg中）
								const msgData = JSON.parse(res.data.msg);

								// 设置默认数据
								this.setDefaultValues(msgData);
							} catch (e) {
								console.error('解析接口数据失败:', e);
								// 解析失败时初始化默认值
								this.initDefaultTypeData();
							}
						} else {
							console.error('接口请求失败:', res.data?.msg || '未知错误');
							this.initDefaultTypeData();
						}
					},
					fail: (err) => {
						console.error('接口调用失败:', err);
						this.initDefaultTypeData();
					}
				});
			},

			// 将接口数据设置为表单默认值
			setDefaultValues(apiData) {
				// 设置展示类型
				if (apiData.type) {
					this.submitData.type = apiData.type;

					// 更新展示类型选择器索引
					const types = ['image', 'list', 'keydata', 'webview'];
					const typeIndex = types.indexOf(apiData.type);
					if (typeIndex !== -1) {
						this.displayTypeIndex = typeIndex;
					}
				}

				// 根据类型设置对应数据
				switch (apiData.type) {
					case 'keydata':
						if (apiData.keydata?.items) {
							this.submitData.keydata.items = [...apiData.keydata.items];
						}
						break;
					case 'list':
						if (apiData.list?.items) {
							this.submitData.list.items = [...apiData.list.items];
						}
						break;
					case 'image':
						if (apiData.image) {
							this.submitData.image = {
								...apiData.image
							};
						}
						break;
					case 'webview':
						if (apiData.webview) {
							this.submitData.webview = {
								...apiData.webview
							};
						}
						break;
				}

				// 设置应用ID（agentid）并匹配选择器
				if (apiData.agentid) {
					this.submitData.agentid = apiData.agentid;
					// 找到对应的选择器索引
					const agentIndex = this.agentIdOptions.findIndex(
						item => item.value === apiData.agentid
					);
					if (agentIndex !== -1) {
						this.agentIdIndex = agentIndex;
					}
				}
			},
			// 应用ID选择器切换事件
			onAgentIdChange(e) {
				const index = e.detail.value;
				this.agentIdIndex = index;
				this.submitData.agentid = this.agentIdOptions[index].value;
				this.fetchDefaultData(this.agentIdOptions[index].value);
			},

			// 切换展示类型
			onDisplayTypeChange(e) {
				const index = e.detail.value;
				this.displayTypeIndex = index;

				// 设置类型值
				const types = ['image', 'list', 'keydata', 'webview'];
				this.submitData.type = types[index];

				// 初始化对应类型的数据结构
				this.initDefaultTypeData();
			},

			// 初始化默认类型的数据
			initDefaultTypeData() {
				switch (this.submitData.type) {
					case 'list':
						if (!this.submitData.list.items || this.submitData.list.items.length === 0) {
							this.submitData.list.items = [{
								title: '',
								jump_url: ''
							}];
						}
						break;
					case 'keydata':
						if (!this.submitData.keydata.items || this.submitData.keydata.items.length === 0) {
							this.submitData.keydata.items = [{
								key: '',
								data: '',
								jump_url: '',
								pagepath: ''
							}];
						}
						break;
				}
			},
			// 新增：添加用户ID项（无上限）
			    addUserId() {
			      this.submitData.userid_list.push(''); // 新增空输入项，支持无限添加
			    },
			    
			    // 新增：删除用户ID项
			    removeUserId(index) {
			      this.submitData.userid_list.splice(index, 1);
			    },
			// 添加列表项
			addListItem() {
				if (this.submitData.list.items.length >= 3) {
					uni.showToast({
						title: '列表项最多支持3个',
						icon: 'none',
						duration: 1500
					});
					return;
				}
				this.submitData.list.items.push({
					title: '',
					jump_url: ''
				});
			},

			// 移除列表项
			removeListItem(index) {
				this.submitData.list.items.splice(index, 1);
			},

			// 添加数据项
			addDataItem() {
				if (this.submitData.keydata.items.length >= 4) {
					uni.showToast({
						title: '数据项最多支持4个',
						icon: 'none',
						duration: 1500
					});
					return;
				}
				this.submitData.keydata.items.push({
					key: '',
					data: '',
					jump_url: '',
					pagepath: ''
				});
			},

			// 移除数据项
			removeDataItem(index) {
				this.submitData.keydata.items.splice(index, 1);
			},

			// 提交配置
			submitConfig() {
				let isValid = true;
				const errorFields = [];

				// 验证基础参数
				if (!this.submitData.agentid) {
					isValid = false;
					errorFields.push('应用ID(agentid)');
				}

				// 根据类型验证对应的内容
				switch (this.submitData.type) {
					case 'image':
						if (!this.submitData.image.url.trim()) {
							isValid = false;
							errorFields.push('图片URL(url)');
						}
						if (!this.submitData.image.jump_url.trim()) {
							isValid = false;
							errorFields.push('跳转链接(jump_url)');
						}
						break;

					case 'list':
						if (!this.submitData.list.items || this.submitData.list.items.length === 0) {
							isValid = false;
							errorFields.push('至少需要一项列表内容');
						} else {
							this.submitData.list.items.forEach((item, index) => {
								if (!item.title.trim()) {
									isValid = false;
									errorFields.push(`列表项 ${index + 1} 的标题(title)`);
								}
								if (!item.jump_url.trim()) {
									isValid = false;
									errorFields.push(`列表项 ${index + 1} 的跳转链接(jump_url)`);
								}
							});
						}
						break;

					case 'keydata':
						if (!this.submitData.keydata.items || this.submitData.keydata.items.length === 0) {
							isValid = false;
							errorFields.push('至少需要一项数据内容');
						} else {
							this.submitData.keydata.items.forEach((item, index) => {
								if (!item.key.trim()) {
									isValid = false;
									errorFields.push(`数据项 ${index + 1} 的键名(key)`);
								}
								if (!item.data.toString().trim()) {
									isValid = false;
									errorFields.push(`数据项 ${index + 1} 的数据值(data)`);
								}
								if (!item.jump_url.trim()) {
									isValid = false;
									errorFields.push(`数据项 ${index + 1} 的跳转链接(jump_url)`);
								}
							});
						}
						break;

					case 'webview':
						if (!this.submitData.webview.title.trim()) {
							isValid = false;
							errorFields.push('页面标题(title)');
						}
						if (!this.submitData.webview.url.trim()) {
							isValid = false;
							errorFields.push('网页URL(url)');
						}
						if (!this.submitData.webview.jump_url.trim()) {
							isValid = false;
							errorFields.push('跳转链接(jump_url)');
						}
						break;
				}

				if (isValid) {
					console.log('提交的JSON数据:', JSON.stringify(this.submitData, null, 2));

					// 显示加载提示
					uni.showLoading({
						title: '提交中...'
					});

					uni.request({
						url: 'http://ziyan.xshhotels.cn:8981/api/NetUpdate/PostDetail',
						method: 'POST',
						data: this.submitData,
						header: {
							'Content-Type': 'application/json'
						},
						success: (res) => {
							uni.hideLoading();
							if (res.data.success) {
								uni.showToast({
									title: '配置提交成功！',
									icon: 'success'
								});
							} else {
								uni.showToast({
									title: '提交失败: ' + (res.data.message || '未知错误'),
									icon: 'none'
								});
							}
						},
						fail: (err) => {
							uni.hideLoading();
							uni.showToast({
								title: '网络错误',
								icon: 'none'
							});
							console.error(err);
						}
					});
				} else {
					uni.showModal({
						title: '输入错误',
						content: `请完善以下必填项：\n${errorFields.join('\n')}`,
						showCancel: false
					});
				}
			}
		}
	};
</script>

<style scoped>
	/* 引入Font Awesome图标库 */
	@import url("https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css");

	.container {
		padding: 16px;
		background-color: #f5f7fa;
		font-family: 'Noto Sans SC', sans-serif;
		color: #333;
		min-height: 100vh;
	}

	.config-section {
		background-color: white;
		border: 1px solid #e5e7eb;
		border-radius: 8px;
		margin-bottom: 16px;
		padding: 16px;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
	}

	.section-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 12px;
		color: #1f2937;
	}

	.section-desc {
		font-size: 13px;
		color: #6b7280;
		margin-bottom: 16px;
		padding-left: 2px;
	}

	.form-item {
		margin-bottom: 16px;
	}

	.form-label {
		font-size: 14px;
		margin-bottom: 6px;
		display: block;
		color: #4b5563;
	}

	.form-input {
		width: 100%;
		height: 40px;
		padding: 0 10px;
		border: 1px solid #d1d5db;
		border-radius: 8px;
		font-size: 14px;
	}

	.form-input:focus {
		border-color: #3b82f6;
		outline: none;
	}

	.submit-btn {
		background-color: #3b82f6;
		color: white;
		height: 45px;
		width: 90%;
		border-radius: 10px;
		font-size: 16px;
		font-weight: 500;
		margin: 20px auto;
		display: block;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8px;
	}

	.submit-btn .fa {
		font-size: 18px;
	}

	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 16px 0 8px;
		font-weight: 500;
	}

	.list-items {
		margin-bottom: 8px;
	}

	.data-item,
	.list-item {
		border: 1px solid #e5e7eb;
		border-radius: 6px;
		padding: 10px;
		margin-bottom: 12px;
	}

	.remove-btn {
		color: #ef4444;
		background: none;
		border: none;
		font-size: 18px;
		width: 36px;
		height: 36px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		transition: background-color 0.2s;
	}

	.remove-btn:hover {
		background-color: rgba(239, 68, 68, 0.1);
	}

	.remove-btn .fa {
		font-size: 16px;
	}

	.add-btn {
		color: #3b82f6;
		background: none;
		border: none;
		font-size: 14px;
		display: flex;
		align-items: center;
		padding: 8px 0;
		margin-top: 8px;
		gap: 6px;
		border-radius: 6px;
		transition: background-color 0.2s;
	}

	.add-btn:hover {
		background-color: rgba(59, 130, 246, 0.1);
	}

	.add-btn .fa {
		font-size: 16px;
	}

	.picker {
		width: 100%;
		height: 40px;
		border: 1px solid #d1d5db;
		border-radius: 8px;
		padding: 0 10px;
		font-size: 14px;
		background-color: white;
		display: flex;
		align-items: center;
	}

	.picker-view {
		width: 100%;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.limit-tip {
		font-size: 14px;
		color: #9ca3af;
		margin-top: 8px;
		padding-left: 2px;
		display: flex;
		align-items: center;
		gap: 6px;
	}

	.limit-tip .fa {
		font-size: 14px;
	}
	/* 新增：用户ID列表样式优化 */
	.userid-list-container {
	  margin-top: 16px;
	}
	
	.userid-items {
	  margin-bottom: 8px;
	}
	
	.userid-item {
	  display: flex;
	  align-items: center;
	  gap: 8px; /* 输入框与删除按钮间距 */
	  margin-bottom: 8px;
	}
	
	.userid-input {
	  flex: 1; /* 输入框占满剩余空间 */
	}
	
	.userid-remove-btn {
	  width: 40px;
	  height: 40px;
	  border-radius: 8px;
	  background-color: #fef2f2;
	}
	
	.userid-add-btn {
	  margin-top: 12px;
	  padding: 8px 0;
	  width: 100%;
	  border: 1px dashed #3b82f6;
	  border-radius: 8px;
	}

</style>